package jobs

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"mongo/logs"
	"strconv"
	"time"
)

type AutoDropCollection struct {
	connectionString string
	database         string
	cron             string
}

func New(connectionString, database, cron string) *AutoDropCollection {
	job := AutoDropCollection{connectionString: connectionString, database: database, cron: cron}
	return &job
}

func (job *AutoDropCollection) Run() {
	fmt.Println("starting to drop the " + job.database + " collections...")
	logs.Logger.Info("starting to drop the " + job.database + " collections...")
	clientOptions := options.Client().ApplyURI(job.connectionString)
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
		logs.Logger.Error(err)
	}
	// check the connection
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
		logs.Logger.Error(err)
	}
	defer client.Disconnect(context.TODO())
	fmt.Println("Connected to MongoDB![" + job.database + "]")
	logs.Logger.Info("Connected to MongoDB![" + job.database + "]")

	opts := options.Count().SetMaxTime(2 * time.Second)
	collectionNames, err := client.Database(job.database).ListCollectionNames(context.TODO(), bson.D{})
	if err != nil {
		log.Fatalln(err)
		logs.Logger.Error(err)
	}
	count := 0
	for i := 0; i < len(collectionNames); i++ {
		name := collectionNames[i]
		fmt.Println(name)
		coll := client.Database(job.database).Collection(name)
		coll.Drop(context.TODO()) // 删除表
		// 全部删除
		//coll.DeleteMany(context.TODO(),bson.D{}) // 删除数据
		count, _ := coll.CountDocuments(context.TODO(), bson.D{}, opts)
		fmt.Println(name + " has " + string(count) + " records.")
		logs.Logger.Info(name + " has " + strconv.FormatInt(count, 10) + " records.")
		count++
	}
	fmt.Println("end drop the " + job.database + " " + strconv.Itoa(count) + " collections.")
	logs.Logger.Info("end drop the " + job.database + " " + strconv.Itoa(count) + " collections.")
	//
	//collection := client.Database("LanGuo").Collection("BrushActiveSuccessLog_202103")
	//count, _ := collection.CountDocuments(context.TODO(), bson.D{}, opts)
	//fmt.Println(count)
}
